<template>
  <div class="home-page">
    <!-- 搜索框 -->
    <div class="search-bar">
      <input
          v-model="keyword"
          class="search-input"
          placeholder="请输入商家/菜品关键词"
          @keyup.enter="handleSearch"
      />
      <el-icon class="search-icon" @click="handleSearch">
        <Search />
      </el-icon>
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-state">
      <el-empty :description="errorMessage" :image-size="200">
        <template #image>
          <el-icon color="#F56C6C" :size="60">
            <Warning />
          </el-icon>
        </template>
      </el-empty>
    </div>

    <!-- 商家分类 -->
    <div class="business-category" v-if="!errorMessage">
      <h3 class="section-title">商家分类</h3>
      <div class="category-list">
        <div
            v-for="category in categories"
            :key="category.type"
            class="category-item"
            @click="goToCategory(category.type)"
        >
          <img :src="category.image" :alt="category.name" class="category-img">
          <p class="category-name">{{ category.name }}</p>
        </div>
      </div>
    </div>

    <!-- 商家列表 -->
    <div class="business-section" v-if="!errorMessage">
      <h3 class="section-title">推荐商家</h3>
      <div v-if="businessList.length > 0" class="business-list">
        <el-card
            v-for="business in businessList"
            :key="business.businessId"
            class="business-card"
            shadow="hover"
            @click="goToBusiness(business.businessId)"
        >
          <div class="business-content">
            <div class="business-image">
              <img :src="business.head" alt="商家图片" class="business-img">
            </div>
            <div class="business-info">
              <h4 class="business-name">{{ business.businessName }}</h4>
              <p class="business-address" style="text-align: center">
                <el-icon><Location /></el-icon>
                {{ business.address }}
              </p>
              <div class="business-rating">
                <el-rate
                    v-model="business.rating"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template="{value}分"
                    :max="5"
                />
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <div v-else class="empty-state">
        <el-empty description="暂无商家数据" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import {
  Search,
  Location,
  Warning
} from '@element-plus/icons-vue';

const router = useRouter();
const keyword = ref('');
const errorMessage = ref('');
const businessList = ref([]);

// 商家分类数据 - 本地数据作为服务降级
const categories = ref([
  { type: 1, name: '汉堡炸鸡', image: '/src/static/image/type/hamburger.png' },
  { type: 2, name: '奶茶饮料', image: '/src/static/image/type/bubble_tea.png' },
  { type: 3, name: '龙虾烧烤', image: '/src/static/image/type/barbecue.png' },
  { type: 4, name: '快餐便当', image: '/src/static/image/type/fast_food.png' },
  { type: 5, name: '日韩料理', image: '/src/static/image/type/sushi.png' },
  { type: 6, name: '火锅串串', image: '/src/static/image/type/hot_pot.png' },
  { type: 7, name: '披萨意面', image: '/src/static/image/type/pizza.png' },
  { type: 8, name: '甜品小吃', image: '/src/static/image/type/dessert.png' }
]);

// 默认商家数据 - 服务降级使用
const defaultBusinessList = ref([
  {
    businessId: 1,
    businessName: '示例商家1',
    head: '/src/static/image/default_business.png',
    address: '示例地址1',
    rating: 4.5
  },
  {
    businessId: 2,
    businessName: '示例商家2',
    head: '/src/static/image/default_business.png',
    address: '示例地址2',
    rating: 4.0
  }
]);

const handleSearch = () => {
  if (keyword.value.trim()) {
    localStorage.setItem('searchKeyword', keyword.value.trim());
    router.push('/search');
  }
};

const goToBusiness = (businessId) => {
  localStorage.setItem('business_id', businessId);
  router.push('/business');
};

const goToCategory = (type) => {
  localStorage.setItem('business_type', type);
  router.push('/business/category');
};

/**
 * 服务降级处理
 * @param {string} type - 错误类型
 */
const handleServiceDegradation = (type) => {
  console.warn(`服务降级处理: ${type}`);

  switch(type) {
    case 'NETWORK_ERROR':
      errorMessage.value = '网络连接异常，已显示本地数据';
      businessList.value = defaultBusinessList.value;
      break;
    case 'SERVER_ERROR':
      errorMessage.value = '服务器异常，已显示本地数据';
      businessList.value = defaultBusinessList.value;
      break;
    case 'AUTH_ERROR':
      errorMessage.value = '登录信息过期，请重新登录';
      localStorage.removeItem('access_token');
      router.push('/login');
      break;
    case 'PERMISSION_ERROR':
      errorMessage.value = '权限不足，已显示部分功能';
      businessList.value = defaultBusinessList.value;
      break;
    default:
      errorMessage.value = '系统繁忙，已显示本地数据';
      businessList.value = defaultBusinessList.value;
  }
};

// 获取business信息列表
const fetchBusinessList = async () => {
  try {
    const token = localStorage.getItem('access_token');
    if (!token) {
      handleServiceDegradation('AUTH_ERROR');
      return;
    }

    const response = await fetch('http://localhost:8080/business/all', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));

      // 根据状态码进行服务降级处理
      switch(response.status) {
        case 401:
          handleServiceDegradation('AUTH_ERROR');
          break;
        case 403:
          handleServiceDegradation('PERMISSION_ERROR');
          break;
        case 500:
        case 502:
        case 503:
          handleServiceDegradation('SERVER_ERROR');
          break;
        default:
          handleServiceDegradation('UNKNOWN_ERROR');
      }
      return;
    }

    const data = await response.json().catch(() => {
      handleServiceDegradation('DATA_ERROR');
      return defaultBusinessList.value;
    });

    businessList.value = data || defaultBusinessList.value;

  } catch (error) {
    console.error('API请求失败:', error);

    // 根据错误类型进行服务降级
    if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
      handleServiceDegradation('NETWORK_ERROR');
    } else {
      handleServiceDegradation('UNKNOWN_ERROR');
    }
  }
};

onMounted(() => {
  const token = localStorage.getItem('access_token');
  if (!token) {
    handleServiceDegradation('AUTH_ERROR');
  } else {
    fetchBusinessList();
  }
});
</script>

<style scoped>
.health-app {
  max-width: 800px;
  margin: 0 auto;
  padding: 12px 12px 80px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 错误提示 */
.error-state {
  padding: 40px 0;
  text-align: center;
  background-color: white;
  border-radius: 12px;
  margin-bottom: 20px;
}

/* 搜索栏 */
.search-bar {
  position: relative;
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  height: 42px;
  border: 1px solid #409eff;
  border-radius: 21px;
  padding: 0 42px 0 15px;
  font-size: 14px;
  outline: none;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  box-sizing: border-box;
}

.search-icon {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 18px;
  color: #409eff;
  cursor: pointer;
  padding: 8px;
}

/* 区块标题 */
.section-title {
  font-size: 16px;
  color: #333;
  margin: 0 0 15px 8px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.section-title::before {
  content: "";
  display: inline-block;
  width: 3px;
  height: 14px;
  background: #409eff;
  border-radius: 2px;
  margin-right: 8px;
}

/* 商家分类 */
.business-category {
  margin-bottom: 20px;
}

.category-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  padding: 0 8px;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: white;
  border-radius: 8px;
  padding: 10px 5px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.category-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.category-img {
  width: 40px;
  height: 40px;
  object-fit: contain;
  margin-bottom: 8px;
}

.category-name {
  font-size: 12px;
  color: #333;
  margin: 0;
  text-align: center;
}

/* 商家列表 */
.business-section {
  margin-bottom: 20px;
}

.business-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.business-card {
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
}

.business-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.business-content {
  display: flex;
  padding: 15px;
  gap: 15px;
}

.business-image {
  width: 90px;
  height: 90px;
  flex-shrink: 0;
  border-radius: 8px;
  overflow: hidden;
}

.business-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.business-card:hover .business-img {
  transform: scale(1.05);
}

.business-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-width: 0;
  margin-left: 5vw;
}

.business-name {
  margin: 0 0 6px 0;
  font-size: 3vw;
  font-weight: bold;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.business-address {
  margin: 0 0 8px 0;
  font-size: 2vw;
  color: #666;
  display: flex;
  align-items: center;
  gap: 4px;
}

.business-address .el-icon {
  font-size: 14px;
  color: #999;
}

.business-rating {
  display: flex;
  align-items: center;
}

/* 空状态 */
.empty-state {
  padding: 40px 0;
  text-align: center;
  background-color: white;
  border-radius: 12px;
}



.nav-item p {
  font-size: 12px;
  color: #999;
  margin: 0;
  transition: all 0.3s ease;
}


/* 响应式调整 */
@media (max-width: 480px) {
  .business-content {
    padding: 12px;
    gap: 12px;
  }

  .business-image {
    width: 80px;
    height: 80px;
  }

  .business-name {
    font-size: 15px;
  }

  .business-address {
    font-size: 12px;
  }

  .nav-container {
    height: 56px;
  }

  .nav-item .el-icon {
    font-size: 20px;
  }

  .nav-item p {
    font-size: 11px;
  }

  .category-list {
    grid-template-columns: repeat(4, 1fr);
  }

  .category-img {
    width: 35px;
    height: 35px;
  }

  .category-name {
    font-size: 11px;
  }
}

@media (min-width: 600px) {
  .business-card {
    border-radius: 16px;
  }

  .business-image {
    width: 100px;
    height: 100px;
  }

  .business-name {
    font-size: 17px;
  }

  .business-address {
    font-size: 14px;
  }

  .nav-container {
    height: 64px;
  }

  .nav-item .el-icon {
    font-size: 24px;
  }

  .nav-item p {
    font-size: 13px;
  }

  .category-list {
    grid-template-columns: repeat(4, 1fr);
  }

  .category-img {
    width: 45px;
    height: 45px;
  }

  .category-name {
    font-size: 13px;
  }
}
</style>